<!--
//
// Trigger.vue
// vue3-element-admin
//
// Created by 区区电脑 on 2023/04/11.
//
-->
<template>
    <div class="Index">
        <!-- 筛选区 -->
        <table-search-bar :config="requestBodyConfig" :model="requestBody" title="定时任务管理" @search="searchClicked" />
        <!-- 内容 -->
        <div class="container">
            <!-- 功能按钮 -->
            <div class="table-buttons">
                <el-button v-permission="permission.sync" type="primary" @click="syncTask">同步任务</el-button>
            </div>
            <!--checkbox设置 :checkbox-config="{trigger: 'row', highlight: true}" -->
            <!--radio设置 :radio-config="{trigger: 'row', highlight: true}" -->
            <vxe-table ref="VXETable" :column-config="{ resizable: false}" :data="state.list" :loading="state.isLoading" :radio-config="{trigger: 'row', highlight: true}" :row-config="{isCurrent: true, isHover: true, keyField: 'id'}" :tree-config="{childrenField: 'children', reserve: true}" border round show-overflow size="small" @current-change="() => {}" @radio-change="() => {}">
                <template #empty>
                    <el-empty :image-size="100" />
                </template>
                <vxe-column fixed="left" title="#" type="seq" width="50" />
                <vxe-column align="left" field="description" :fixed="$fixedColumn('left')" min-width="260" title="名称" type="expand">
                    <template #default="{ row }">
                        <span>{{ row.description }}</span>
                    </template>
                    <template #content="{ row }">
                        <div>
                            <TriggerTable :list="row.jobTriggers" :options="row" @reload="reload" />
                        </div>
                    </template>
                </vxe-column>
                <vxe-column field="status" title="状态" width="120">
                    <template #default="{ row }">
                        <div v-if="row.status === 1" class="status">
                            <div class="pointer open"></div>
                            <span class="open-text">正常</span>
                        </div>
                        <div v-else class="status">
                            <div class="pointer"></div>
                            <span class="text">停止</span>
                        </div>
                    </template>
                </vxe-column>
                <vxe-column field="jobId" title="Code" width="200"></vxe-column>
                <vxe-column field="concurrent" title="执行类型" width="120">
                    <template #default="{ row }">
                        <el-tag v-if="row.concurrent">并行</el-tag>
                        <el-tag v-else type="warning">串行</el-tag>
                    </template>
                </vxe-column>

                <vxe-column field="groupName" title="分组" width="200"></vxe-column>
                <vxe-column field="updatedTime" title="更新时间" width="200">
                    <template #default="{ row }">
                        <span>{{ filters.dateFilter(row.updatedTime) }}</span>
                    </template>
                </vxe-column>
                <vxe-column :resizable="false" field="action" fixed="right" title="操作" :width="$widthColumn(150)">
                    <template #default="{row}">
                        <table-action :actions="[
                            {title: '修改', permission: permission.edit, type: 'primary', ok: editData},
                            {title: '删除', permission: permission.delete, type: 'danger', ok: deleteData, confirm: '您确定要删除当前数据么?'},
                            {title: '停止', show: row.status === 1, permission: permission.stop, type: 'primary', ok: () => startOrStopTask(row, 0), inMore: true},
                            {title: '启动', show: row.status !== 1, permission: permission.start, type: 'primary', ok: () => startOrStopTask(row, 1), inMore: true},
                            {title: '查看日志', permission: permission.log, type: 'primary', ok: showLogData, inMore: true},
                            {title: '添加触发器', permission: permission.addTrigger, type: 'primary', ok: addTriggerData, inMore: true},
                        ]" :data="row" />
                    </template>
                </vxe-column>
            </vxe-table>
            <!--            <div class="page-config">-->
            <!--                <vxe-pager v-model:current-page="requestParams.pageIndex" v-model:page-size="requestParams.pageSize" :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" :page-sizes="pageConfig.sizes" :total="pageConfig.total" background size="mini" @page-change="onPageChange" />-->
            <!--            </div>-->
        </div>
    </div>
    <EditForm ref="editForm" />
    <AddTrigger ref="addTrigger" />
    <ShowLog ref="showLog" />
</template>

<script setup>
import {ref, reactive, computed, onMounted} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import * as api from "./api.js"
import EditForm from "./EditForm.vue"
import TriggerTable from "./components/Trigger.vue"
import AddTrigger from "./components/EditForm.vue"
import ShowLog from "./ShowLog.vue";

const {$dayjs, $message, $fixedColumn, $widthColumn} = window;

const props = defineProps({});
const emits = defineEmits();

// 路由
const router = useRouter();
// store
const store = useStore();
// 响应式数据
const state = reactive({
    // 表格数据加载中
    isLoading: false,
    // 表格数据
    list: []
})
// 过滤器
const filters = computed(() => {
    return {
        dateFilter(val) {
            if (!val) return ""
            return $dayjs(val).format("YYYY-MM-DD HH:mm:ss")
        }
    }
})

// 当前页面功能权限
const permission = {
    sync: "TaskJobDetail:SyncTaskJob",
    start: "TaskJobDetail:StartTaskJob",
    stop: "TaskJobDetail:StopTaskJob",
    trigger: "TaskJobTrigger:GetJobTriggerList",
    edit: "TaskJobDetail:UpdateTaskJobDetail",
    delete: "TaskJobDetail:DeleteTaskJobDetail",
    log: "SysTaskLog:GetTaskLogPageList",
    addTrigger: "TaskJobTrigger:AddTaskJobTrigger"
};

// 请求query参数
const requestParams = reactive({
    orderCol: "jobId",
    isDesc: false,
    pageIndex: 1,
    pageSize: 20,
});
// 请求body参数
const requestBody = reactive({
    status: null,
})
// 筛选区域配置
const requestBodyConfig = reactive({
    //name: {label: "名称", component: "el-input"},
    //code: {label: "编号", component: "el-input", inMore: true},
    status: {label: "状态", component: "el-select", data: [{name: "正常", value: 1}, {name: "停止", value: 0}]},
    //createdTime: {label: "创建时间", component: "el-date-picker", format: "YYYY-MM-DD", inMore: true},
    //updateTime: {label: "更新时间", component: "el-date-picker-datetime", format: "YYYY-MM-DD HH:mm:ss", inMore: true}
})
// 分页配置
const pageConfig = reactive({
    total: 0,
    sizes: [10, 20, 50, 100, 200]
})


const editForm = ref();

// 同步任务
function syncTask() {
    console.log("同步任务")
    api.SyncTaskJob().then(({success}) => {
        if (success) {
            $message.success("同步成功");
            reload();
        }
    });
}


// 删除
async function deleteData({jobId}) {
    console.log("删除: ", jobId)
    const {success, data} = await api.DeleteTaskJobDetail({jobId});
    if (!success) return 0;
    reload();
    $message.success("删除成功")
}

// 修改
function editData(row) {
    editForm.value.show({
        title: "修改",
        options: {...row},
        ok: () => {
            reload();
        }
    })
}

// 启动、停止任务
function startOrStopTask(row, status) {
    if (status === 1) {
        api.StartTaskJob({jobId: row.jobId}).then(({success}) => {
            if (success) {
                $message.success("任务已启动");
                reload();
            }
        });
    } else {
        api.StopTaskJob({jobId: row.jobId}).then(({success}) => {
            if (success) {
                $message.success("任务已停止");
                reload();
            }
        });
    }
}

// 添加触发器
const addTrigger = ref();

function addTriggerData(row) {
    const params = {
        jobId: row.jobId,
        description: row.description + "触发器",
        startTime: $dayjs().format("YYYY-MM-DD HH:mm:ss"),
        endTime: $dayjs("9999-01-01 00:00:00").format("YYYY-MM-DD HH:mm:ss"),
        strCron: "* * * * *",
        cronType: 0,
        maxNumberOfRuns: 0,
        maxNumberOfErrors: 0,
        numRetries: 0,
    }
    addTrigger.value.show({
        title: "添加",
        options: params,
        ok: () => {
            reload();
        }
    })
}

// 点击搜索
function searchClicked() {
    console.primary("搜索条件: ", requestBody)
    reload(true);
}

// 查询列表
async function loadList() {
    const body = {
        ...requestBody
    };
    state.isLoading = true;
    const {success, data} = await api.GetJobDetailList(body);
    state.isLoading = false;
    if (!success) return 0;
    state.list = data;
}

// 查看日志
const showLog = ref();

function showLogData(row) {
    showLog.value.show({
        title: `${row.description} 日志`,
        options: {...row}
    })
}


// 分页事件
function onPageChange({type}) {
    if (type === "current") {
        loadList()
    }
    if (type === "size") {
        reload(true)
    }
}

// 刷新
function reload(resetPageIndex) {
    if (resetPageIndex) requestParams.pageIndex = 1;
    loadList()
}


onMounted(() => {
    loadList()
})
</script>

<style lang="scss" scoped>
.Index {
    margin: 10px;
    width: calc(100% - 20px);
    box-sizing: border-box;

    .container {
        padding: 10px;
        background: #fff;
        margin-top: 10px;
        box-shadow: 0 0 10px -2px rgba(0, 0, 0, 0.1);
    }
}

.status {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;

    .pointer {
        width: 8px;
        height: 8px;
        border-radius: 10px;
        background: #f5222d;
    }

    .open {
        background: #36b368;
        position: relative;

        &::after {
            content: " ";
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 1;
            background: #36b368;
            opacity: 1;
            animation: openanim 1.2s ease infinite;
            border-radius: 10px;
        }
    }

    .text {
        color: #f5222d;
        padding-left: 8px;
    }

    .open-text {
        color: #36b368;
        padding-left: 8px;
    }
}

@keyframes openanim {
    0% {
        transform: scale(1);
        opacity: 1;
    }
    100% {
        transform: scale(2);
        opacity: 0;
    }
}
</style>
